package com.qny.ai.aop;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class RequestLogAspect {

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void anyRestController() {}

    @Around("anyRestController()")
    public Object aroundController(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = null;
        if (ra instanceof ServletRequestAttributes sra) {
            req = sra.getRequest();
        }
        String uri = req != null ? req.getRequestURI() : "N/A";
        String method = req != null ? req.getMethod() : "N/A";
        String signature = pjp.getSignature().toShortString();
        String args = Arrays.toString(pjp.getArgs());
        log.info("[API] -> {} {} | {} args={}", method, uri, signature, args);
        try {
            Object ret = pjp.proceed();
            long cost = System.currentTimeMillis() - start;
            log.info("[API] <- {} {} | {}ms | resp={}", method, uri, cost, safeToString(ret));
            return ret;
        } catch (Throwable t) {
            long cost = System.currentTimeMillis() - start;
            log.error("[API] !! {} {} | {}ms | ex={}", method, uri, cost, t.toString(), t);
            throw t;
        }
    }

    private String safeToString(Object obj) {
        try { return String.valueOf(obj); } catch (Exception e) { return "<unprintable>"; }
    }
}


